<template>
	<view class="index">
		<!-- 1.地图 -->
		<map id="myMap" v-bind:latitude="start.latitude" v-bind:longitude="start.longitude" v-bind:markers="markers"
			:include-points="points" :polyline="polyline" :key="polyline.length + new Date().getTime()"></map>

		<!-- 2.mask -->
		<view class="mask" v-if="!findCar">
			<view class="maskItem" v-if="distance">
				<view class="place">
					距离：{{distance}} 时间：{{duration}}
				</view>
			</view>

			<!-- 第一部分 -->
			<view class="maskItem">
				<image class="pic" src="/static/myaddress.png" mode=""></image>
				<view class="place">
					{{start.name}}
				</view>
				<text class="now" @click="chooseLocation">当前</text>
			</view>

			<!-- 第二部分 -->
			<view class="maskItem" @click="toDestination">
				<image class="pic" src="/static/redaddress.png" mode=""></image>
				<view class="place" v-if="target.name">
					{{target.district}}{{target.name}}
				</view>
				<view class="place" v-else>
					请选择目的地
				</view>
			</view>
			<!-- 第三部分 -->
			<view class="maskItem" v-if="target.length!=0 && !haveOrder">
				<button type="primary" style="width: 100%;background-color: #58f;" @click="origination">一键叫车</button>
			</view>
		</view>

		<view class="mask" v-else>
			<view class="maskItem">
				等待司机接单...
			</view>
			<view class="maskItem">
				<button type="primary" style="width: 100%;background-color: #58f;">取消订单</button>
			</view>
		</view>

	</view>
</template>

<script>
	//1.导入插件
	import amapFile from '@/libs/amap-wx.js'
	import utils from "../../common/utils.js"
	import uniIcons from "@/components/uni-icons/uni-icons.vue";
	const api = utils.websiteUrl;
	export default {
		data() {
			return {
				myAmapFun: undefined,
				start: {
					name: '',
					address: '',
					longitude: 30.0011111,
					latitude: 89.1111111
				},
				//定义经纬度
				// longitude: '',
				// latitude: '',
				markers: [],
				//存放目的地
				target: '',
				order: {}, //订单
				findCar: false, //判断乘客是否发起订单
				getCar: false, //判断乘客是否上车
				token: '',
				points: [], //地图缩放，显示所有点
				distance: 0, //距离
				duration: 0, //时间
				flag: 10, //路径策略
				tripInfo: {},
				polyline: [],
				haveOrder: false, // 判断是否有进行中的订单




			}
		},
		onLoad() {
			//2.创建实例对象，以便于后面调用它的方式，实现相关功能
			//传入自己的key
			this.myAmapFun = new amapFile.AMapWX({
				key: '85208405250c458368d44bccd8104998'
			});

			//3.调用方法获取位置信息(可以封装成一个函数)
			//在加载时调用位置信息
			this.getLocation();
			uni.setStorageSync('target', '')
			this.token = uni.getStorageSync('token')
			this.points = []
			// this.getAllOrder()
			// if (this.haveOrder) {
			// 	this.haveOrder = true
			// }



		},
		onUnload() {
			uni.setStorageSync('target', '')

		},
		onShow() {
			let str = decodeURIComponent(uni.getStorageSync('target') ||
			[]) //解决Error in onLoad hook: “SyntaxError: Unexpected end of JSON i错误nput“
			this.target = str ? JSON.parse(str) : '请选择目的地'
			// this.target = uni.getStorageInfoSync('target') ? JSON.parse(uni.getStorageSync('target')) : '请选择目的地'
			if (this.target.location) {
				var temp = this.target.location
				this.target.longitude = temp.split(',')[0]
				this.target.latitude = temp.split(',')[1]
			}
			if (this.target.latitude) {
				let obj = {
					id: 1,
					latitude: this.target.latitude,
					longitude: this.target.longitude,
					iconPath: "../../static/终点.png",
					width: 40,
					height: 40
				}
				this.markers.push(obj)
			}

			let opt = {
				latitude: this.target.latitude,
				longitude: this.target.longitude
			}

			let start = this.start.longitude + ',' + this.start.latitude
			let end = this.target.longitude + ',' + this.target.latitude
			this.flag = 10

			if (opt.latitude) {
				this.points.push(opt)
				this.getPlanningRoute(start, end, 10)
			}



		},
		methods: {
			//获取当前位置信息的函数
			getLocation() {
				const that = this;
				//调用方法获取位置信息
				this.myAmapFun.getRegeo({
					//成功的回调函数(获取位置信息成功)
					success: (res) => {
						console.log('当前位置信息', res);
						this.start.name = res[0].desc;
						this.start.longitude = res[0].longitude;
						this.start.latitude = res[0].latitude;
						console.log(res[0].desc);
						console.log(this.start)

						//添加标记点
						let obj = {
							id: 0,
							latitude: this.start.latitude,
							longitude: this.start.longitude,
							iconPath: "../../static/start.png",
							width: 50,
							height: 50
						}
						let opt = {
							latitude: this.start.latitude,
							longitude: this.start.longitude
						}
						this.points.push(opt)

						this.markers = []
						this.markers.push(obj)
					},
					//失败的回调函数(获取位置信息失败)
					fail: (err) => {
						console.log('获取位置失败0', err);
					}
				})
			},
			// 选择位置
			chooseLocation() {
				let that = this
				uni.chooseLocation({
					success: function(res) {
						console.log(res)
						that.start = res
						// this.start.name = res.name
						// this.start.address = res.address
						// this.start.latitude = res.latitude
						// this.start.longitude = res.longitude

						console.log('位置名称：' + res.name);
						console.log('详细地址：' + res.address);
						console.log('纬度：' + res.latitude);
						console.log('经度：' + res.longitude);
						//添加标记点
						let obj = {
							id: 1,
							latitude: that.start.latitude,
							longitude: that.start.longitude,
							iconPath: "../../static/start.png",
							width: 50,
							height: 50
						}
						// this.markers.splice(0)

						this.markers = []
						this.markers.push(obj)



					},
					fail: () => {
						uni.switchTab({
							url: "/pages/index/index"
						})
					}
				});
			},
			// 跳转到地点选择
			toDestination() {
				uni.navigateTo({
					url: "/pages/destination/destination"
				})
			},
			// 乘客发起打车请求
			origination() {
				let that = this;
				// if (that.haveOrder) {
				// 	uni.showToast({
				// 		duration: 1000,
				// 		title: "已存在进行中的订单",
				// 		position: 'center'
				// 	})
				// } else 
				if (that.start && that.target != "请选择目的地") {
					uni.request({
						url: api + "/order/origination",
						method: 'GET',
						sslVerify: false,
						data: {
							"positionStartLongitude": that.start.longitude,
							"positionStartLatitude": that.start.latitude,
							"positionEndLatitude": that.target.latitude,
							"positionEndLongitude": that.target.longitude

						},
						header: {
							'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
							"token": that.token
						},
						success: (res) => {
							console.log(res);
							if (res.data.code == '0') {
								that.order = res.data.data
								that.findCar = true
								uni.switchTab({
									url: "/pages/index/index"
								})
							}
							if (res.data.code == '1') {
								uni.showToast({
									duration: 1000,
									title: "您已存在进行中订单",
									position: 'center',
									icon: 'error'
								})
								that.findCar = true
								uni.switchTab({
									url: "/pages/index/index"
								})
							}
						},
						fail: (err) => {
							console.log(err)
						}
					})
					// that.findCar = true
					// uni.switchTab({
					// 	url:"/pages/index/index"
					// })
				} else {
					uni.showToast({
						title: "请选择目的地",
						duration: 1000,
						position: 'center',
						icon: 'error'
					})
				}
			},
			/**
			 *@Description:生成规划路线
			 *@param {string} start 开始位置 this.startPoint.longitude + ',' + this.startPoint.latitude
			 *@param {string} end 结束位置 this.endPoint.longitude + ',' + this.endPoint.latitude
			 *@param {number} strategy 10 默认多策略 策略 https://lbs.amap.com/api/webservice/guide/api/direction#driving
			 *
			 10，返回结果会躲避拥堵，路程较短，尽量缩短时间，与高德地图的默认策略也就是不进行任何勾选一致
			 * 4，躲避拥堵，但是可能会存在绕路的情况，耗时可能较长
			 2，距离优先，仅走距离最短的路线，但是可能存在穿越小路/小区的情况
			 */
			getPlanningRoute(start, end, strategy = 10) {
				let that = this
				uni.showLoading({
					title: '加载中'
				});
				that.myAmapFun.getDrivingRoute({
					origin: start,
					destination: end,
					strategy: strategy, //备选方案
					success: function(data) {
						// console.log('所有路径',data)
						if (data.paths && data.paths[0] && data.paths[0].steps) {
							// 默认 10 会 对返回多条路径的方案  按照时间短的
							let goodRouter = data.paths.sort((a, b) => {
								return a.duration - b.duration
							})[0]

							that.distance = (goodRouter.distance * 0.001).toFixed(2) + '公里'
							that.duration = '大约' + (goodRouter.duration / 60).toFixed(2) + '分钟'

							let steps = goodRouter.steps
							let points = []
							for (var i = 0; i < steps.length; i++) {
								var poLen = steps[i].polyline.split(';');
								for (var j = 0; j < poLen.length; j++) {
									points.push({
										longitude: parseFloat(poLen[j].split(',')[0]),
										latitude: parseFloat(poLen[j].split(',')[1])
									})
								}
							}
							that.polyline = [{
								points: points,
								color: strategy === 10 ? '#0ee532' : strategy === 2 ? '#0742d9' :
									'#ee6b06',
								width: 8,
							}]
						}
						uni.hideLoading();
					},
					fail: function(info) { //失败回调
						console.log('路线规划失败')
						console.log(info)
						uni.hideLoading();
						uni.showToast({
							title: '路线规划失败',
							icon: 'error'
						});
					},
				})
			},
			getAllOrder() {
				let that = this;
				uni.request({
					url: api + "order/getAllOrder",
					method: 'GET',
					data: {

					},
					sslVerify: false,
					header: {
						'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
						'token': that.token
					},
					success: (res) => {
						console.log(res)
						if (res.data.code == '0') {
							console.log('获取所有订单s')
							console.log(res)
							that.haveOrder = true
							that.order = res.data.data
							that.markers = []
							let start1 = {
								id: 0,
								latitude: that.order.positionStartLatitude,
								longitude: that.order.positionStartLongitude,
								iconPath: "../../static/起点.png",
								width: 50,
								height: 50
							}
							let end1 = {
								id: 1,
								latitude: that.order.positionEndLatitude,
								longitude: that.order.positionEndLongitude,
								iconPath: "../../static/终点.png",
								width: 50,
								height: 50
							}
							that.markers.push(start1)
							that.markers.push(end1)
							that.points = []
							let start2 = {
								latitude: that.order.positionStartLatitude,
								longitude: that.order.positionStartLongitude
							}
							let end2 = {
								latitude: that.order.positionEndLatitude,
								longitude: that.order.positionEndLongitude,
							}
							that.points.push(start2)
							that.points.push(end2)
							// that.getPlanningRoute(start2, end2, 10)
						} else {
							console.log('获取所有订单e')
							console.log(res)
						}
					},
					fail: (err) => {
						console.log("获取所有订单f" + err)
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.index {
		width: 100vw;
		height: 100vh;

		//地图
		#myMap {
			width: 100vw;
			height: 100vh;
		}

		//mask
		.mask {
			//左右间隙分别占一份
			width: 98vw;
			background-color: #fff;
			//固定定位
			position: fixed;
			left: 1vw;
			bottom: 1vw;
			box-shadow: 1px 1px 4px 4px #ccc;

			.maskItem {
				//width:100%
				height: 120rpx;
				border: 1px solid #eee;
				display: flex;
				padding: 0 40rpx;
				align-items: center;

				.pic {
					width: 50rpx;
					height: 50rpx;
					margin-right: 40rpx;
				}

				.place {
					//让当前元素占满现在的位置
					flex: 1;
					color: #999;
				}

				.now {
					width: 50rpx;
					height: 50rpx;
					background-color: #58f;
					//文字颜色
					color: #fff;

					font-size: 25rpx;
					padding: 8rpx;
					align-items: center;
					border-radius: 5px;
				}
			}
		}
	}
</style>